%%
%Cell 1
%Init

clc;
f=2000000; %2MHz
a=1000000000000;
tao=0.000005;

%%
%Cell 2
% When fs=1GHz,The figure of s12.

fs=50000000;%1GHz
y=zeros(2*tao*fs+1,1);
count1=1;

clc;
for t=0:1/fs:2*tao
    y(count1,1)=sin(2*pi*f*t)*exp(-a*(t-tao)*(t-tao)/2);
    count1=count1+1;
end

plot(y,'r');
hold on;

%%
%Cell 3
%Relay
clc;
fs=50000000;%1GHz
deltat1=0.000000205;
deltat2=0.000000210;
deltat3=0.000000215;

zero1=zeros(deltat1*fs,1);
zero2=zeros(deltat2*fs,1);
zero3=zeros(deltat3*fs,1);

plot(cat(1,zero1,y),'g');
plot(cat(1,zero2,y),'b');
plot(cat(1,zero3,y),'y');

legend('ORIGIN','205ns','210ns','215ns')
%%
%Cell 4
%
clc;
correlation1=xcorr(cat(1,zero1,y),y);
index1=find(correlation1==max(correlation1))-511;
index1
correlation2=xcorr(cat(1,zero2,y),y);
index2=find(correlation2==max(correlation2))-511;
index2
correlation3=xcorr(cat(1,zero3,y),y);
index3=find(correlation3==max(correlation3))-511;
index3
%%
%Cell 5
%
count2=1;

rocordx=0.1:0.1:1;
rocordy=0.1:0.1:1;

rocord1z=zeros(10,10);
rocord2z=zeros(10,10);
rocord3z=zeros(10,10);

clc;
for xn=1:1:10
    for yn=1:1:10
random1=randn(length(cat(1,zero1,y)),1);
random2=randn(length(y),1);
correlation1=xcorr(cat(1,zero1,y)+random1*xn/10.0,y+random2*yn/10.0);
index1=find(correlation1==max(correlation1))-10001;

if abs(index1/2-205)<100
rocord1z(xn,yn)=index1/2-205;
else
    rocord1z(xn,yn)=0;
end
    

random3=randn(length(cat(1,zero2,y)),1);
random4=randn(length(y),1);
correlation2=xcorr(cat(1,zero2,y)+random3*xn/10.0,y+random4*yn/10.0);
index2=find(correlation2==max(correlation2))-10001;

if abs(index2/2-205)<100
rocord2z(xn,yn)=index2/2-205;
else
    rocord2z(xn,yn)=0;
end

random5=randn(length(cat(1,zero3,y)),1);
random6=randn(length(y),1);
correlation3=xcorr(cat(1,zero3,y)+random5*xn/10.0,y+random6*yn/10.0);
index3=find(correlation3==max(correlation3))-10001;

if abs(index3/2-205)<100
rocord3z(xn,yn)=index3/2-205;
else
    rocord3z(xn,yn)=0;
end

count2=count2+1;
    end
end

surfc(rocordx,rocordy,rocord3z);

%%
%Cell 6
%
x=1:1021;
xx=1:0.05:1021;
chzhi=spline(x,y,xx);

clc;

chzhi1=spline(x,cat(1,zero1,y),xx);
p=find(chzhi1==max(chzhi1))-10001;
p/2

yc=correlation2;
c2=spline(x,yc,xx);
c3=c2';
p=find(c3==max(c3))-10001;
p/2

yc=correlation3;
c2=spline(x,yc,xx);
c3=c2';
p=find(c3==max(c3))-10001;
p/2
